//
//  RDReader.m
//  readApp
//
//  Created by 飞猪 on 2018/8/16.
//  Copyright © 2018年 😝😝😝😝😝. All rights reserved.
//

#import "RDReader.h"
#import "RDContainerPageViewController.h"
#import "RDDataParser.h"
#import "RDTableView.h"
#import "RDAttributedView.h"
#import "RDStatusBar.h"
#import "RDTextDataParser.h"
#import "RDNetworkTool.h"

@interface RDReader ()
<
UIPageViewControllerDelegate,
UIPageViewControllerDataSource,
KAAdInterstitialDelegate,
KAAdBannerDelegate
>

@property (nonatomic, strong) RDContainerPageViewController *pageViewController;

@property (nonatomic, strong) RDTableView *tableView;

@property (nonatomic, strong) RDTextDataParser *dataParser;

// 解析后的所有章节model
@property (nonatomic, strong) NSMutableDictionary<NSString *, RDChapterModel *> *totalChapterModels;

// chapter model cache
@property (nonatomic, strong) NSMutableDictionary<NSString *, RDChapterModel *> *chapterModels;

//@property (nonatomic, strong) RDChapterModel *model;

// 是否重分页
@property (nonatomic) BOOL isReCutPage;

// 章节缓存（分页后的页面数组）
@property (nonatomic, strong) NSMutableDictionary<NSString *, NSArray<RDPageModel *> *> *chapterCaches;

// 缓存队列
@property (nonatomic, strong) dispatch_queue_t cacheQueue;

// 页面饥饿
@property (nonatomic) BOOL pageHunger;

// 设置字体颜色
@property (nonatomic) BOOL changeCharColor;

// 设置字体
@property (nonatomic) BOOL changeCharFont;

/// 当前页面
@property (nonatomic) NSInteger currentPageIndex;
/// 当前章节 索引
@property (nonatomic, copy  ) NSString *currentChapterIndex;

/// 对table view而言，status bar是放在reader view上的，其他模式则是放在每个page页面上
@property (nonatomic, strong) RDStatusBar *statusBarForTableView;

/// 首次进阅读器
@property (nonatomic) BOOL firstIntoReader;

/// 重分页后如何定位阅读进度？
/// 首先记录分页前当前页面首字符在本章的索引，重分页后根据索引确定用户先前看的页面在章节中新的位置
@property (nonatomic) NSInteger prePageStartLocation;

/// 是否成功切换到某章节，成功为@""，不成功则记录未成功切换的章节index，当指定跳至某章节时使用
@property (nonatomic, copy  ) NSString *successSwitchChapter;

@property (nonatomic, strong) KAAdInterstitial *interstitial;

@property (nonatomic, strong) NSMutableArray<NSString *> *saveChapters;

#pragma mark - 横幅广告
@property (nonatomic, strong) KAAdBanner *banner;

@end

@implementation RDReader

#pragma mark - Overwrite
- (void)viewDidLoad {
    [super viewDidLoad];
  
  [self.view addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(pagingTaped:)]];
  
  [self loadReaderView];
  [self addObserverForConfiguration];
  
  self.cacheQueue = dispatch_queue_create("reader.cache.queue", 0);
  self.currentPageIndex = 1;
  self.currentChapterIndex = @"";
  self.firstIntoReader = YES;
  self.prePageStartLocation = -1;
  self.successSwitchChapter = nil;
  
//  [self beginRead];
}

- (void)viewWillAppear:(BOOL)animated {
  [super viewWillAppear:animated];
  
  [UIApplication sharedApplication].statusBarHidden = YES;
}

- (void)viewWillDisappear:(BOOL)animated {
  [super viewWillDisappear:animated];
  
  [UIApplication sharedApplication].statusBarHidden = NO;
}

- (void)addObserverForConfiguration {
  __weak typeof(RDReader) *wkSelf = self;
  self.config.charColorChanged = ^(UIColor *color) {
    [wkSelf reloadDayOrNight];
  };
  
  self.config.fontNameChanged = ^(NSString *fontName) {
    [wkSelf reloadFont];
  };
  
  // 阅读背景图片
  self.config.readerBGImageChanged = ^(UIImage *img) {
    [wkSelf reloadDayOrNight];
  };
}

#pragma mark - Event
- (void)reloadDayOrNight {
  RDChapterModel *chapter = self.chapterModels[self.currentChapterIndex];
  self.changeCharColor = YES;
  [self readWith:chapter pageIndex:self.currentPageIndex];
}

- (void)reloadFont {
  RDChapterModel *chapter = self.chapterModels[self.currentChapterIndex];
  self.changeCharFont = YES;
  [self readWith:chapter pageIndex:self.currentPageIndex];
}

- (void)reloadReader {
  self.isReCutPage = YES;
  
  if (self.prePageStartLocation == -1) {
    NSArray<RDPageModel *> *pageArray = [self pageArrayFromCache:self.currentChapterIndex];
    
    self.prePageStartLocation = pageArray[self.currentPageIndex].range.location;
  }
  RDChapterModel *chapter = self.chapterModels[self.currentChapterIndex];
  [self readWith:chapter pageIndex:self.currentPageIndex];
}

- (void)beginWithParam:(NSDictionary *)params {
  [self beginRead:params];
}

- (void)beginRead:(NSDictionary *)params {
  
  if (!params || ![params objectForKey:@"chId"] || [[params objectForKey:@"chId"] isEqualToString:@""] || ![params objectForKey:@"bookId"] || [[params objectForKey:@"bookId"] isEqualToString:@""]) {
    [SVProgressHUD showErrorWithStatus:@"参数有误！"];
    [self dismissViewControllerAnimated:YES completion:nil];
    return;
  }
  
  [self requestForContent:params callback:^(RDNETChapterModel *chapterModel) {
    RDNETChapterModel *chModel = chapterModel;
    RDChapterModel *model = [self.dataParser parseChapterFromModel:chModel];
    self.currentChapterIndex = model.chId;
    [self.totalChapterModels setObject:model forKey:self.currentChapterIndex];
    
    [self readWith:model pageIndex:1];
  } show:YES];
}

- (void)setCurrentChapterIndex:(NSString *)currentChapterIndex {
  _currentChapterIndex = currentChapterIndex;
  
  if (self.delegate && [self.delegate respondsToSelector:@selector(reader:updateModel:)]) {
    [self.delegate reader:self updateModel:[self.chapterModels objectForKey:_currentChapterIndex]];
  }
}

- (void)pagingTaped:(UITapGestureRecognizer *)ges {
  
  // 阅读页设置 有效点击区域为 屏幕宽度的1/3
  CGPoint tapPoint = [ges locationInView:self.view];
  CGRect validRect = CGRectMake(kScreenWidth / 3.0, 0, kScreenWidth / 3.0, kScreenHeight);
  if (CGRectContainsPoint(validRect, tapPoint)) {
    if (self.delegate && [self.delegate respondsToSelector:@selector(readerSettingClicked:chapterModel:)]) {
      RDChapterModel *model = [self.chapterModels objectForKey:self.currentChapterIndex];
      model.curPage = [@(self.statusBarForTableView.curPageIndex + 1) stringValue];
      model.totalPage = self.statusBarForTableView.totalPageCounts;
      
      NSMutableArray *pageArray = [self pageArrayFromCache:self.currentChapterIndex];
      if (pageArray.count > 0) {
        RDPageModel *pageModel = pageArray[self.statusBarForTableView.curPageIndex];
        NSString *str;
        if (pageModel.attributedString.string.length > 80) {
          str = [pageModel.attributedString.string substringToIndex:80];
        }
        else {
          str = pageModel.attributedString.string;
        }
        model.curPageIntro = [str stringByReplacingOccurrencesOfString:@"\n\t" withString:@""];
      }
      else {
        model.curPageIntro = @"";
      }
      
      [self.delegate readerSettingClicked:self chapterModel:model];
    }
  }
  
}

#pragma mark - CreateView
- (void)loadReaderView {
  
  // 阅读容器
  [self loadPageViewController];
  
  // 阅读背景图片
  if(self.config.readerBGImage) {
    [self loadBackgroundImage];
  }
}

- (void)loadPageViewController {
  
//  self.clearReaderViewIfNeed()
  
//  let transtionStyle: UIPageViewControllerTransitionStyle = (self.config.scrollType == .curl) ? .pageCurl : .scroll
//  self.pageVC?.isDoubleSided = (self.config.scrollType == .curl) ? true : false

  UIPageViewControllerTransitionStyle style = UIPageViewControllerTransitionStylePageCurl;
  
  // 创建 UIPageViewController
  RDContainerPageViewController *pageViewController = [[RDContainerPageViewController alloc] initWithTransitionStyle:style navigationOrientation:UIPageViewControllerNavigationOrientationHorizontal options:nil];
  self.pageViewController = pageViewController;
  pageViewController.dataSource = self;
  pageViewController.delegate = self;
  pageViewController.doubleSided = YES; // 双面显示
  
  // 添加到父控制器中
  [self addChildViewController:pageViewController];
  [pageViewController didMoveToParentViewController:self];
  
  [self.view addSubview:pageViewController.view];
}

- (void)loadBackgroundImage {
  
  //        var curPage: DUAPageViewController? = nil
  //        if config.scrollType == .curl {
  //            curPage = pageVC?.viewControllers?.first as? DUAPageViewController
  //            if curPage != nil {
  //                let imageView = curPage?.view.subviews.first as! UIImageView
  //                imageView.image = self.config.backgroundImage
  //            }
  //        }
  //        if config.scrollType == .horizontal || config.scrollType == .none {
  //            curPage = translationVC?.childViewControllers.first as? DUAPageViewController
  //            if curPage != nil {
  //                let imageView = curPage?.view.subviews.first as! UIImageView
  //                imageView.image = self.config.backgroundImage
  //            }
  //        }
  
  UIView *firstView = [self.view.subviews firstObject];
  if (firstView && [firstView isKindOfClass:[UIImageView class]]) {
    ((UIImageView *)firstView).image = self.config.readerBGImage;
  }
  else {
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:self.view.bounds];
    imageView.image = self.config.readerBGImage;
    [self.view insertSubview:imageView atIndex:0];
  }
}

#pragma mark - APIs
- (void)readWithFilePath:(NSString *)filePath pageIndex:(NSInteger)pageIndex {
//  self.postReaderStateNotification(state: .busy)
  [self.dataParser parseChapterFromBook:filePath completeHandler:^(NSArray<NSString *> *titles, NSArray<RDChapterModel *> *models) {
    
//    if self.delegate?.reader(reader: chapterTitles: ) != nil {
//      self.delegate?.reader(reader: self, chapterTitles: titles)
//    }
    
//    self.totalChapterModels = models;
//    [self readWith:models.firstObject pageIndex:pageIndex];
  }];
}

//- (void)readChapterAtChapterIndex:(NSString *)chapterId pageIndex:(NSInteger)pageIndex {
- (void)readChapterAtChapterIndex:(RDChapterModel *)chapterModel pageIndex:(NSInteger)pageIndex {
  
  if (chapterModel && chapterModel.chId && chapterModel.chId.length > 0) {
    NSArray<RDPageModel *> *pageModels = [self pageArrayFromCache:chapterModel.chId];
    if (pageModels.count <= 0) {
      self.successSwitchChapter = chapterModel.chId;
      [self postReaderStateNotification:RDReaderStateBusy];
      [self requestChapterWith:chapterModel.chId cover:YES];
    }
    else {
      self.successSwitchChapter = nil;
      self.currentPageIndex = pageIndex <= 0 ? 0 : (pageIndex - 1);
      [self updateChapterIndex:chapterModel.chId];
      if (![self.currentChapterIndex isEqualToString:chapterModel.chId]) {
        
        /// 判断预缓存方向
        BOOL forward = NO;
        if ([self.currentChapterIndex isEqualToString:chapterModel.preChId]) {
          forward = NO;
        }
        else if ([self.currentChapterIndex isEqualToString:chapterModel.nextChId]) {
          forward = YES;
        }
        else {
          forward = YES;
        }
        self.currentChapterIndex = chapterModel.chId;
        [self forwardCacheIfNeed:forward];
      }
      
      [self loadPage:self.currentPageIndex];
      //      if self.delegate?.reader(reader: readerProgressUpdated: curPage: totalPages: ) != nil {
      //        self.delegate?.reader(reader: self, readerProgressUpdated: currentChapterIndex, curPage: currentPageIndex + 1, totalPages: self.pageArrayFromCache(chapterIndex: currentChapterIndex).count)
      //      }
    }
  }

//  if (chapterId && chapterId.length > 0) {
//    NSArray<RDPageModel *> *pageModels = [self pageArrayFromCache:chapterId];
//    if (pageModels.count <= 0) {
//      self.successSwitchChapter = chapterId;
//      [self postReaderStateNotification:RDReaderStateBusy];
//      [self requestChapterWith:chapterId cover:YES];
//    }
//    else {
//      self.successSwitchChapter = @"";
//      self.currentPageIndex = pageIndex <= 0 ? 0 : (pageIndex - 1);
//      [self updateChapterIndex:chapterId];
//      [self loadPage:self.currentPageIndex];
////      if self.delegate?.reader(reader: readerProgressUpdated: curPage: totalPages: ) != nil {
////        self.delegate?.reader(reader: self, readerProgressUpdated: currentChapterIndex, curPage: currentPageIndex + 1, totalPages: self.pageArrayFromCache(chapterIndex: currentChapterIndex).count)
////      }
//    }
//  }
  
}

- (void)readWithParam:(NSDictionary *)params {
  
  NSString *chId = [params objectForKey:@"chId"];
//  NSString *bookId = [params objectForKey:@"bookId"];
  RDChapterModel *chapterModel = [self.totalChapterModels objectForKey:chId];
  
  if (chapterModel) {
    self.currentChapterIndex = chapterModel.chId;
    [self readWith:chapterModel pageIndex:1];
  }
  else {
    
    [self requestForContent:params callback:^(RDNETChapterModel *NETChapterModel) {
      RDChapterModel *model = [self.dataParser parseChapterFromModel:NETChapterModel];
      self.currentChapterIndex = model.chId;
      [self.totalChapterModels setObject:model forKey:self.currentChapterIndex];
      
      [self readWith:model pageIndex:1];
    } show:YES];
  }
  
}

#pragma mark - Notification
- (void)postReaderStateNotification:(RDReaderState)state {
  dispatch_async(dispatch_get_main_queue(), ^{
    if (self.delegate && [self.delegate respondsToSelector:@selector(reader:state:)]) {
      [self.delegate reader:self state:state];
    }
  });
}

#pragma mark - Priavte
- (void)readWith:(RDChapterModel *)chapter pageIndex:(NSInteger)pageIndex {
  
  [self.chapterModels setValue:chapter forKey:chapter.chId];
  
  if ([NSThread isMainThread] == NO) {
    [self forwardCacheWith:chapter];
    return;
  }
  
  NSArray<RDPageModel *> *pageModels = @[];
  if (self.isReCutPage) { // 重新分页
    [self postReaderStateNotification:RDReaderStateBusy];
    [self.chapterCaches removeAllObjects];
  }
  else if (self.changeCharColor) {
    self.changeCharColor = NO;
    self.pageHunger = YES;
    [self.chapterCaches removeAllObjects];
  }
  else if (self.changeCharFont) {
    self.changeCharFont = NO;
    self.pageHunger = YES;
    [self.chapterCaches removeAllObjects];
  }
  else {
    pageModels = [self pageArrayFromCache:chapter.chId];
  }
  
  if (pageModels.count == 0 || self.isReCutPage) {
    
    dispatch_async(self.cacheQueue, ^{
      
      NSMutableArray<RDPageModel *> *pageModels = [self pageArrayFromCache:chapter.chId];
      if (pageModels.count > 0) {
        return;
      }
      
      // 富文本
      NSAttributedString *attrString = [self.dataParser attributedStringFromChapterModel:chapter config:self.config];
      
      [self.dataParser cutPageWith:attrString config:self.config completeHandler:^(NSInteger completedPageCounts, RDPageModel *page, BOOL completed) {
        [pageModels addObject:page];
        if (completed) {
          [self cachePageArray:pageModels chapterIndex:chapter.chId];
          
          dispatch_async(dispatch_get_main_queue(), ^{
            [self processPageArray:pageModels chapter:chapter pageIndex:pageIndex];
          });
        }
      }];
      
    });
  }
}

- (void)forwardCacheWith:(RDChapterModel *)chapter {
  
  NSMutableArray<RDPageModel *> *pageArray = [NSMutableArray array];
  NSAttributedString *attrString = [self.dataParser attributedStringFromChapterModel:chapter config:self.config];
  [self.dataParser cutPageWith:attrString config:self.config completeHandler:^(NSInteger completedPageCounts, RDPageModel *page, BOOL completed) {
    [pageArray addObject:page];
    if (completed) {
      [self cachePageArray:pageArray chapterIndex:chapter.chId];
      NSLog(@"预缓存完成");
      
      if (self.pageHunger) {
        dispatch_async(dispatch_get_main_queue(), ^{
          [self postReaderStateNotification:RDReaderStateReady];
          self.pageHunger = NO;
          if (self.pageViewController != nil) {
            [self loadPage:self.currentPageIndex];
          }
          if (self.tableView != nil) {
//            if self.currentPageIndex == 0 && self.tableView?.scrollDirection == .up {
//              self.requestLastChapterForTableView()
//            }
//            if self.currentPageIndex == self.pageArrayFromCache(chapterIndex: self.currentChapterIndex).count - 1 && self.tableView?.scrollDirection == .down {
//              self.requestNextChapterForTableView()
//            }
          }
        });
      }
    }
  }];
}

- (NSMutableArray<RDPageModel *> *)pageArrayFromCache:(NSString *)chapterIndex {
  NSArray *pageArray = [self.chapterCaches objectForKey:chapterIndex];
  if (pageArray) {
    return pageArray.mutableCopy;
  }
  else {
    return @[].mutableCopy;
  }
}

- (void)cachePageArray:(NSArray<RDPageModel *> *)pageModels chapterIndex:(NSString *)chapterIndex {
  [self.chapterCaches setObject:pageModels forKey:chapterIndex];
  ///     for item in self.chapterCaches.keys {
  ///         if Int(item)! - currentChapterIndex > 2 || Int(item)! - currentChapterIndex < -1 {
  ///             self.chapterCaches.removeValue(forKey: item)
  ///         }
  ///     }
}

- (void)processPageArray:(NSArray<RDPageModel *> *)pageModels chapter:(RDChapterModel *)chapterModel pageIndex:(NSInteger)pageIndex {
  
  [self postReaderStateNotification:RDReaderStateReady];
  if (self.pageHunger) {
    self.pageHunger = NO;
    if (self.pageViewController) {
      [self loadPage:self.currentPageIndex];
    }
    if (self.tableView) {
//      if currentPageIndex == 0 && tableView?.scrollDirection == .up {
//        self.requestLastChapterForTableView()
//      }
//      if currentPageIndex == self.pageArrayFromCache(chapterIndex: currentChapterIndex).count - 1 && tableView?.scrollDirection == .down {
//        self.requestNextChapterForTableView()
//      }
    }
  }
  
  if (self.firstIntoReader) {
    self.firstIntoReader = NO;
    
    self.currentPageIndex = pageIndex <= 0 ? 0 : (pageIndex - 1);
    [self updateChapterIndex:chapterModel.chId];
    self.currentChapterIndex = chapterModel.chId;
    [self loadPage:self.currentPageIndex];
    
    /// 触发预缓存
    [self forwardCacheIfNeed: YES];
    [self forwardCacheIfNeed: NO];
    
//    if self.delegate?.reader(reader: readerProgressUpdated: curPage: totalPages: ) != nil {
//      self.delegate?.reader(reader: self, readerProgressUpdated: currentChapterIndex, curPage: currentPageIndex + 1, totalPages: self.pageArrayFromCache(chapterIndex: currentChapterIndex).count)
//    }
  }
  
  if (self.isReCutPage) {
    self.isReCutPage = NO;
    
    NSInteger newIndex = 1;
    for (int index = 0; index < pageModels.count; ++index) {
      RDPageModel *item = pageModels[index];
      if ((self.prePageStartLocation >= item.range.location) && self.prePageStartLocation <= item.range.location + item.range.length) {
        newIndex = index;
      }
      
    }
    self.currentPageIndex = newIndex;
    [self loadPage:self.currentPageIndex];
    
    /// 触发预缓存
    [self forwardCacheIfNeed: YES];
    [self forwardCacheIfNeed: NO];
  }
  
  if (self.successSwitchChapter && ![self.successSwitchChapter isEqualToString:@""]) {
    [self readChapterBy:self.successSwitchChapter pageIndex: 1];
  }
}

- (void)readChapterBy:(NSString *)index pageIndex:(NSInteger)pageIndex {
  RDChapterModel *model = [self.totalChapterModels objectForKey:index];
  if (model) {
    if ([self pageArrayFromCache:index].count <= 0) {
      self.successSwitchChapter = index;
      [self postReaderStateNotification:RDReaderStateBusy];
      [self requestChapterWith:index cover:YES];
    }
    else {
      self.successSwitchChapter = nil;
      self.currentPageIndex = pageIndex <= 0 ? 0 : (pageIndex - 1);
      [self updateChapterIndex:index];
      if (![self.currentChapterIndex isEqualToString:index]) {
        
        /// 判断预缓存方向
        BOOL forward = NO;
        if ([self.currentChapterIndex isEqualToString:model.preChId]) {
          forward = NO;
        }
        else if ([self.currentChapterIndex isEqualToString:model.nextChId]) {
          forward = YES;
        }
        else {
          forward = YES;
        }
        self.currentChapterIndex = index;
        [self forwardCacheIfNeed:forward];
      }
      
      [self loadPage: self.currentPageIndex];
//      if self.delegate?.reader(reader: readerProgressUpdated: curPage: totalPages: ) != nil {
//        self.delegate?.reader(reader: self, readerProgressUpdated: currentChapterIndex, curPage: currentPageIndex + 1, totalPages: self.pageArrayFromCache(chapterIndex: currentChapterIndex).count)
//      }
    }
  }
}

- (void)updateChapterIndex:(NSString *)index {
  if ([self.currentChapterIndex isEqualToString:index]) {
    return;
  }
  NSLog(@"进入第 %@ 章", index);
  if (self.delegate && [self.delegate respondsToSelector:@selector(reader:chapter:)]) {
    NSArray<RDPageModel *> *pageModels = [self pageArrayFromCache:index];
    RDChapterModel *model = [self.chapterModels objectForKey:index];
    model.totalPage = pageModels.count;
    model.curPage = @"1";
    [self.delegate reader:self chapter:model];
  }
  
//  BOOL forward = ([self.currentChapterIndex integerValue] > [index integerValue]) ? NO : YES;
//  self.currentChapterIndex = index;
//
//  /// 每当章节切换时触发预缓存
//  [self forwardCacheIfNeed:forward];
}

/// 为何要预缓存？
/// 本阅读器是按照逐个章节的方式阅读的（便于分章阅读，例如连载小说等），如果当前章节阅读结束时请求下一章数据
/// 那么章节解析分页均会耗时（当然你可以不等分页全部完成就直接展示已经分好的页面，以减少用户等待，那是另一套
/// 逻辑了）。因此每当用户跨入新的一章，程序自动触发当前章下一章的请求，提前准备好数据，以实现章节无缝切换
///
/// - Parameter forward: 向前缓存还是向后缓存
- (void)forwardCacheIfNeed:(BOOL)forward {
  
  RDChapterModel *model = [self.totalChapterModels objectForKey:self.currentChapterIndex];
  
  NSString *predictIndex = forward ? model.nextChId : model.preChId;
  if (!predictIndex || [predictIndex isEqualToString:@"0"] || [predictIndex isEqualToString:@""]) {
    return;
  }
  
  dispatch_async(self.cacheQueue, ^{
    NSArray *nextPageArray = [self pageArrayFromCache:predictIndex];
    if (nextPageArray.count <= 0) {
      NSLog(@"执行预缓存 章节 %@", predictIndex);
      [self requestChapterWith:predictIndex cover:NO]; // NO
    }
  });
}

// 获取下一章节内容
- (void)requestChapterWith:(NSString *)index cover:(BOOL)show {
  NSArray *pages = [self pageArrayFromCache:index];
  if (pages.count > 0) {
    return;
  }
  
  /// 这里在书籍解析后直接保存了所有章节model，故直接取即可
  RDChapterModel *model = [self.totalChapterModels objectForKey:self.currentChapterIndex];
  RDChapterModel *chapter = [self.totalChapterModels objectForKey:index];
  if (chapter) {
//    self.model = chapter;
      [self readWith:chapter pageIndex:1];
  }
  else {
//    RDChapterModel *chapterModel = self.model;
    NSDictionary *params = @{
                             @"chId": index,
                             @"bookId": model.bookId
                             };
    [self requestForContent:params callback:^(RDNETChapterModel *NETChapterModel) {
      RDChapterModel *model = [self.dataParser parseChapterFromModel:NETChapterModel];
      [self.totalChapterModels setObject:model forKey:index];
      
      [self readWith:model pageIndex:1];
    } show:show];
  }
  
  /// 对于分章节阅读的情况，每个章节可能需要通过网络请求获取，完成后调用readWithchapter方法即可
}

- (void)loadPage:(NSInteger)pageIndex {
  //        switch self.config.scrollType {
  //        case .curl:
  RDPageViewController *page = [self getPageVCWith:pageIndex chapterIndex:self.currentChapterIndex];
  if (page == nil) {
    return;
  }
  
  NSMutableArray *pageArray = [self pageArrayFromCache:self.currentChapterIndex];
  if (self.delegate && [self.delegate respondsToSelector:@selector(reader:curChapter:curPage:totalPages:curPageContent:)]) {
    
    NSString *str;
    if (pageArray.count > 0) {
      RDPageModel *pageModel = pageArray[self.statusBarForTableView.curPageIndex];
      if (pageModel.attributedString.string.length > 80) {
        str = [pageModel.attributedString.string substringToIndex:80];
      }
      else {
        str = pageModel.attributedString.string;
      }
      str = [str stringByReplacingOccurrencesOfString:@"\n\t" withString:@""];
    }
    else {
      str = @"";
    }
    
    [self.delegate reader:self curChapter:self.currentChapterIndex curPage:pageIndex + 1 totalPages:pageArray.count curPageContent:str];
  }
  
  [self.pageViewController setViewControllers:@[page] direction:UIPageViewControllerNavigationDirectionForward animated:NO completion:nil];
  //        case .vertical:
  //            print("load table view page")
  //            tableView?.dataArray.removeAll()
  //            tableView?.dataArray = self.pageArrayFromCache(chapterIndex: currentChapterIndex)
  //            self.tableView?.cellIndex = pageIndex
  //            if tableView?.dataArray == nil {
  //                return
  //            }
  //
  //            self.tableView?.isReloading = true
  //            self.tableView?.reloadData()
  //            self.tableView?.scrollToRow(at: IndexPath.init(row: tableView!.cellIndex, section: 0), at: UITableViewScrollPosition.top, animated: false)
  //            self.tableView?.isReloading = false
  //
  //            self.statusBarForTableView?.totalPageCounts = (tableView?.dataArray.count)!
  //            self.statusBarForTableView?.curPageIndex = currentPageIndex
  //
  //            /// 当加载的页码为最后一页，需要手动触发一次下一章的请求
  //            if self.currentPageIndex == self.pageArrayFromCache(chapterIndex: self.currentChapterIndex).count - 1 {
  //                self.requestNextChapterForTableView()
  //            }
  //        case .horizontal:
  //            let page = self.getPageVCWith(pageIndex: pageIndex, chapterIndex: self.currentChapterIndex)
  //            if page == nil {
  //                return
  //            }
  //            self.translationVC?.setViewController(viewController: page!, direction: .left, animated: false, completionHandler: nil)
  //        case .none:
  //            let page = self.getPageVCWith(pageIndex: pageIndex, chapterIndex: self.currentChapterIndex)
  //            if page == nil {
  //                return
  //            }
  //            self.translationVC?.setViewController(viewController: page!, direction: .left, animated: false, completionHandler: nil)
  
  //        }
}


/// 仿真、平移、无动画翻页模式使用
///
/// - Parameters:
///   - pageIndex: 页面索引
///   - chapterIndex: 章节索引
/// - Returns: 单个page页面
- (RDPageViewController *)getPageVCWith:(NSInteger)pageIndex chapterIndex:(NSString *)chapterIndex {
  
  RDPageViewController *page = [[RDPageViewController alloc] init];
  page.index = pageIndex;
  page.chapterBelong = chapterIndex;
  if (self.config.readerBGImage) {
    page.backgroundImage = self.config.readerBGImage;
  }
  
  RDAttributedView *dtLabel = [[RDAttributedView alloc] initWithFrame:CGRectMake(0, self.config.contentFrame.origin.y, self.view.width, self.config.contentFrame.size.height)];
  
  dtLabel.edgeInsets = UIEdgeInsetsMake(0, self.config.contentFrame.origin.x, 0, self.config.contentFrame.origin.x);
  
  NSMutableArray *pageArray = [self pageArrayFromCache:chapterIndex];
  if (!pageArray || pageArray.count <= 0) {
    return nil;
  }
  if (pageIndex >= pageArray.count) {
    return nil;
  }
  RDPageModel *pageModel = pageArray[pageIndex];
  dtLabel.attributedString = pageModel.attributedString;
  dtLabel.backgroundColor = [UIColor clearColor];
  [page.view addSubview:dtLabel];
  
  RDChapterModel *chapterModel = [self.chapterModels objectForKey:chapterIndex];
  [self addStatusBarTo:page.view title:chapterModel.chName];
  [self addTabBarTo:page.view totalCounts:pageArray.count curPage:pageIndex];
  
  return page;
}

- (void)addTabBarTo:(UIView *)view totalCounts:(NSInteger)totalCounts curPage:(NSInteger)curPage {
  
  CGFloat safeAreaBottomHeight = [self isFringeScreen] ? 34 : 0;
  CGRect rect = CGRectMake(self.config.contentFrame.origin.x,  kScreenHeight - 30 - safeAreaBottomHeight, self.config.contentFrame.size.width, 20);
  
  RDStatusBar *statusBar = [[RDStatusBar alloc] initWithFrame:rect];
  statusBar.backgroundColor = [UIColor clearColor];
  [view addSubview:statusBar];
  statusBar.totalPageCounts = totalCounts;
  statusBar.curPageIndex = curPage;
  self.statusBarForTableView = statusBar;
  
  if (curPage != 0 && curPage % 5 == 0) {
    // 横幅广告
    [self showBannerAdvert];
  }
  
}

// 横幅广告
- (void)showBannerAdvert {
  
  if (!self.banner) {
    KAAdBanner *banner = [[KAAdBanner alloc] initWithSlot:@"QrmWalGe" withSize:KAAdBannerSize320x50 delegate:self currentController:self];
    self.banner = banner;
    [banner load];
  }
  
}

#pragma mark - KAAdBannerDelegate
- (void)bannerAdCompleteLoadingWithAd:(nonnull KAAdBanner *)bannerAd {
  
//  [self.adContainerView addSubview:bannerAd];
  [self.view addSubview:bannerAd];
  CGFloat xxx = 0;
  if ([self isFringeScreen]) {
    xxx = 34.f;
  }
  [bannerAd setPosition:CGPointMake(kScreenWidth * 0.5, (kScreenHeight - 50) + 25 - xxx)];
  
  UIButton *closeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
  [closeBtn setImage:[UIImage imageNamed:@"close"] forState:UIControlStateNormal];
  [bannerAd addSubview:closeBtn];
  closeBtn.frame = CGRectMake(CGRectGetWidth(bannerAd.frame) - 28, 0, 28, 28);
  [closeBtn addTarget:self action:@selector(closeBanner) forControlEvents:UIControlEventTouchUpInside];
}

- (void)bannerAdFailedLoadingForSlot:(nonnull NSString *)adSlot
                          withStatus:(nonnull NSError *)nativeAdStatus
                           andBanner:(nonnull KAAdBanner *)bannerAd {
  [bannerAd load];
}

- (void)closeBanner {
  [self.banner dismissBanner];
  [self.banner removeFromSuperview];
  self.banner = nil;
}

- (BOOL)isFringeScreen {
  if(@available(iOS 11.0, *)) {
    return !UIEdgeInsetsEqualToEdgeInsets([UIApplication sharedApplication].windows.firstObject.safeAreaInsets, UIEdgeInsetsZero);
  }
  else {
    return NO;
  }
}

- (void)addStatusBarTo:(UIView *)view title:(NSString *)title {
  CGRect rect;
  if ([self isFringeScreen]) {
    rect = CGRectMake(self.config.contentFrame.origin.x,  0, self.config.contentFrame.size.width, 44);
  }
  else {
    rect = CGRectMake(self.config.contentFrame.origin.x,  0, self.config.contentFrame.size.width, 20);
  }
  
  RDStatusBar *statusBar = [[RDStatusBar alloc] initWithFrame:rect];
  statusBar.backgroundColor = [UIColor clearColor];
  [view addSubview:statusBar];
  
  
  if (self.delegate && [self.delegate respondsToSelector:@selector(reader:chapterTitle:)]) {
    [self.delegate reader:self chapterTitle:title];
  }
  
  statusBar.label.text = title;
}

#pragma mark - Network
- (void)requestForContent:(NSDictionary *)params callback:(void(^)(RDNETChapterModel *))callback show:(BOOL)isShow {
  
  if (isShow) {
    [SVProgressHUD showWithStatus:@"加载中..."];
    [SVProgressHUD setFont:[UIFont boldSystemFontOfSize:14.f]];
    [SVProgressHUD setForegroundColor:[UIColor grayColor]];
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeBlack];
    [SVProgressHUD setDefaultStyle:SVProgressHUDStyleDark];
    [SVProgressHUD setDefaultAnimationType:SVProgressHUDAnimationTypeNative];
  }
  
  [RDNetworkTool requestForChapter:params successBlock:^(RDNETChapterModel *chapterModel) {
    
    if (isShow) {
      if (callback) callback(chapterModel);
      dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [SVProgressHUD dismiss];
      });
    }
    else {
      if (callback) callback(chapterModel);
    }
    
  } failBlock:^(NSString *errorMsg) {
    if (isShow) {
      [SVProgressHUD dismiss];
      
      dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
          [SVProgressHUD showErrorWithStatus:errorMsg];
      });
    }
    else {
      [SVProgressHUD showErrorWithStatus:errorMsg];
    }
    [self dismissViewControllerAnimated:YES completion:nil];
  }];
  
}

#pragma mark - UIPageViewControllerDatasource
// 当前界面的上一个界面，该代理在手势操作时便触发（轻微滑动），并且应该是有某种缓存机制，同一界面的第二次手势操作不触发
- (nullable UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerBeforeViewController:(UIViewController *)viewController {
  
  NSLog(@"向前翻页");
  
  BOOL arrived = NO;
  
  if ([viewController isKindOfClass:RDPageViewController.class]) {
    RDPageViewController *page = (RDPageViewController *)viewController;
    RDBackViewController *backPage = [[RDBackViewController alloc] init];
    NSInteger nextIndex = page.index - 1;
    if (nextIndex < 0) {
      RDChapterModel *model = [self.totalChapterModels objectForKey:self.currentChapterIndex];
      if (!model || [model.preChId isEqualToString:@"0"] || [model.preChId isEqualToString:@""]) {
        return nil;
      }
      
      arrived = YES;
      
      self.pageViewController.willStepIntoLastChapter = YES;
      [self requestChapterWith:model.preChId cover:NO];
      
      nextIndex = [self pageArrayFromCache:model.preChId].count - 1;
      RDPageViewController *nextPage = [self getPageVCWith:nextIndex chapterIndex:model.preChId];
      ///         需要的页面并没有准备好，此时出现页面饥饿
      if (nextPage == nil) {
        [self postReaderStateNotification:RDReaderStateBusy];
        self.pageHunger = YES;
        return nil;
      }
      else {
        [backPage grabViewController:nextPage];
        return backPage;
      }
    }
    
    [backPage grabViewController:[self getPageVCWith:nextIndex chapterIndex:page.chapterBelong]];
    return backPage;
    
  }
  
  RDBackViewController *back = (RDBackViewController *)viewController;

  if (arrived) {
    arrived = NO;
    
    return [self getPageVCWith:back.index chapterIndex:back.chapterBelong];
  }
  
  return [self getPageVCWith:back.index chapterIndex:back.chapterBelong];
  
}

// 当前界面的下一个界面，机理同上
- (nullable UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerAfterViewController:(UIViewController *)viewController {
  
  NSLog(@"向后翻页");
  
  static BOOL arrived = NO;
  
  NSInteger nextIndex;
  NSArray *pageArray = [self pageArrayFromCache:self.currentChapterIndex];
  
  if ([viewController isKindOfClass:[RDPageViewController class]]) {
    RDPageViewController *page = (RDPageViewController *)viewController;
    nextIndex = page.index + 1;
    if (nextIndex == pageArray.count) {
      arrived = YES;
    }
    RDBackViewController *backPage = [[RDBackViewController alloc] init];
    [backPage grabViewController:page];
    return backPage;
  }
  if (arrived) {
    arrived = NO;
    RDChapterModel *model = [self.totalChapterModels objectForKey:self.currentChapterIndex];
    if (!model || [model.nextChId isEqualToString:@"0"] || [model.nextChId isEqualToString:@""]) {
      return nil;
    }
    self.pageViewController.willStepIntoNextChapter = YES;
    [self requestChapterWith:model.nextChId cover:NO]; // NO
    RDPageViewController *nextPage = [self getPageVCWith:0 chapterIndex:model.nextChId];
    ///         需要的页面并没有准备好，此时出现页面饥饿
    if (nextPage == nil) {
      [self postReaderStateNotification:RDReaderStateBusy];
      self.pageHunger = YES;
    }
    return nextPage;
  }
  
  RDBackViewController *back = (RDBackViewController *)viewController;
  return [self getPageVCWith:back.index + 1 chapterIndex:back.chapterBelong];
}

#pragma mark - UIPageViewControllerDelegate
// 跳转动画完成时触发，配合上面的代理方法可以定位到具体的跳转界面，此方法有利于定位具体的界面位置，便于日后的管理
// 当用户从一个页面转向下一个或者前一个页面,或者当用户开始从一个页面转向另一个页面的途中后悔了,并撤销返回到了之前的页面时,将会调用这个方法。假如成功跳转到另一个页面时,transitionCompleted 会被置成 YES,假如在跳转途中取消了跳转这个动作将会被置成 NO。

- (void)pageViewController:(UIPageViewController *)pageViewController didFinishAnimating:(BOOL)finished previousViewControllers:(NSArray<UIViewController *> *)previousViewControllers transitionCompleted:(BOOL)completed {
  
  [self containerController:0 currentController:pageViewController.viewControllers.firstObject finished:completed previousController:previousViewControllers.firstObject];
  
}

// 插屏广告
- (void)showInsertAdvert {
  
  if (self.interstitial) {
    self.interstitial = nil;
  }
  
  self.interstitial = [[KAAdInterstitial alloc] initWithSlot:@"ENAORRGW" delegate:self];
  [self.interstitial load];
}

#pragma mark - KAAdInterstitialDelegate
- (void)interstitialAdLoadDidSuccess:(nonnull KAAdInterstitial *) interstitialAd {
  // Warning: Attempt to present <KAAdNativeInterstitial: 0x1037e8280> on <HKLTabBarController: 0x105859400> whose view is not in the window hierarchy!
  if (self.view.window) {
    [self.interstitial presentFromRootViewController:self];
  }
}

- (void) interstitialAdDidDismiss:(nonnull KAAdInterstitial *) interstitial {
  self.interstitial = nil;
}

- (void)containerController:(NSInteger)type currentController:(UIViewController *)currentController finished:(BOOL)finished previousController:(UIViewController *)previousController {
  
  self.prePageStartLocation = -1;
  
  RDPageViewController *curPage = (RDPageViewController *)currentController;
  RDPageViewController *previousPage = (RDPageViewController *)previousController;
  
  NSLog(@"当前页面所在章节 %@ 先前页面所在章节 %@", curPage.chapterBelong, previousPage.chapterBelong);
  if (![curPage.chapterBelong isEqualToString:previousPage.chapterBelong] && ![self.saveChapters containsObject:curPage.chapterBelong] && ![self.saveChapters containsObject:previousPage.chapterBelong]) {
    [self showInsertAdvert];
    NSLog(@"**************************插屏广告******************************************");
    [self.saveChapters removeAllObjects];
    [self.saveChapters addObjectsFromArray:@[curPage.chapterBelong, previousPage.chapterBelong]];
  }
  
  self.currentPageIndex = curPage.index;
  
  BOOL didStepIntoLastChapter = NO;
  BOOL didStepIntoNextChapter = NO;
  if (type == 0) {
    NSInteger cur = [curPage.chapterBelong integerValue];
    NSInteger pre = [previousPage.chapterBelong integerValue];
    didStepIntoLastChapter = self.pageViewController.willStepIntoLastChapter && (cur < pre);
    didStepIntoNextChapter = self.pageViewController.willStepIntoNextChapter && (cur > pre);
  }
  else {
//    didStepIntoLastChapter = (translationVC?.willStepIntoLastChapter)! && curPage.chapterBelong < previousPage.chapterBelong
//    didStepIntoNextChapter = (translationVC?.willStepIntoNextChapter)! && curPage.chapterBelong > previousPage.chapterBelong
  }
  
  RDChapterModel *model = [self.totalChapterModels objectForKey:self.currentChapterIndex];
  if (didStepIntoNextChapter) {
    NSLog(@"进入下一章");
    [self updateChapterIndex:model.nextChId];
    if (![self.currentChapterIndex isEqualToString:model.nextChId]) {
      self.currentChapterIndex = model.nextChId;
      [self forwardCacheIfNeed:YES];  /// 预缓存方向
    }
    
    if (type == 0) {
      self.pageViewController.willStepIntoLastChapter = YES;
      self.pageViewController.willStepIntoNextChapter = NO;
    }
    else {
//      translationVC?.willStepIntoLastChapter = true
//      translationVC?.willStepIntoNextChapter = false
    }
    
  }
  if (didStepIntoLastChapter) {
    NSLog(@"进入上一章");
    [self updateChapterIndex:model.preChId];
    if (![self.currentChapterIndex isEqualToString:model.preChId]) {
      self.currentChapterIndex = model.preChId;
      [self forwardCacheIfNeed:NO];  /// 预缓存方向
    }
    
    if (type == 0) {
      self.pageViewController.willStepIntoNextChapter = YES;
      self.pageViewController.willStepIntoLastChapter = NO;
    }
    else {
//      translationVC?.willStepIntoNextChapter = true
//      translationVC?.willStepIntoLastChapter = false
    }
    
  }
  
  if (self.currentPageIndex != 0) {
    if (type == 0) {
      self.pageViewController.willStepIntoLastChapter = NO;
    }
    else {
//      translationVC?.willStepIntoLastChapter = false
    }
    
  }
  if (self.currentPageIndex != [self pageArrayFromCache: self.currentChapterIndex].count - 1) {
    if (type == 0) {
      self.pageViewController.willStepIntoNextChapter = NO;
    }
    else {
//      translationVC?.willStepIntoNextChapter = false
    }
    
  }
  
  ///     进度信息必要时可以通过delegate回调出去
//  NSLog(@"当前阅读进度 章节 %@ 总页数 %zd 当前页 %zd", self.currentChapterIndex, [self pageArrayFromCache:self.currentChapterIndex].count, self.currentPageIndex + 1);
  NSMutableArray *pageArray = [self pageArrayFromCache:self.currentChapterIndex];
  if (self.delegate && [self.delegate respondsToSelector:@selector(reader:curChapter:curPage:totalPages:curPageContent:)]) {
    
    NSString *str;
    if (pageArray.count > 0) {
      if (self.statusBarForTableView.curPageIndex > pageArray.count - 1) {
        self.statusBarForTableView.curPageIndex = 0;
      }
      RDPageModel *pageModel = pageArray[self.statusBarForTableView.curPageIndex];
      if (pageModel.attributedString.string.length > 80) {
        str = [pageModel.attributedString.string substringToIndex:80];
      }
      else {
        str = pageModel.attributedString.string;
      }
      str = [str stringByReplacingOccurrencesOfString:@"\n\t" withString:@""];
    }
    else {
      str = @"";
    }
    
    [self.delegate reader:self curChapter:self.currentChapterIndex curPage:self.currentPageIndex + 1 totalPages:pageArray.count curPageContent:str];
  }
  
}


#pragma mark - Lazyload
- (RDTextDataParser *)dataParser {
  if (!_dataParser) {
    _dataParser = [[RDTextDataParser alloc] init];
  }
  return _dataParser;
}

- (NSMutableDictionary<NSString *, RDChapterModel *> *)totalChapterModels {
  if (!_totalChapterModels) {
    _totalChapterModels = [NSMutableDictionary dictionary];
  }
  return _totalChapterModels;
}

- (NSMutableDictionary<NSString *, RDChapterModel *> *)chapterModels {
  if (!_chapterModels) {
    _chapterModels = [NSMutableDictionary dictionary];
  }
  return _chapterModels;
}

- (NSMutableDictionary<NSString *,NSArray<RDPageModel *> *> *)chapterCaches {
  if (!_chapterCaches) {
    _chapterCaches = [NSMutableDictionary dictionary];
  }
  return _chapterCaches;
}

- (NSMutableArray<NSString *> *)saveChapters {
  if (!_saveChapters) {
    _saveChapters = [NSMutableArray array];
  }
  return _saveChapters;
}

@end
